package com.hskn.hss.module.file.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hskn.hss.core.exception.file.FileSizeLimitExceededException;
import com.hskn.hss.core.exception.file.InvalidExtensionException;
import com.hskn.hss.core.utils.file.FileUploadUtils;
import com.hskn.hss.core.utils.file.MimeTypeUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.file.service.IFileService;
import com.hskn.hss.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-04-30
 */
@Slf4j
@RestController
@RequestMapping("/hss/file")
public class FileController {

    @Autowired
    private IFileService fileService;

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public AjaxResult<Object> upload(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            String url = fileService.upload(params);
            return AjaxResult.success(url);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("上传失败");
        }
    }

    @PostMapping("/uploadFile")
    public AjaxResult<Object> uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile files) {

        // 这样就可以收到文件了，files.length == 1.
        try {
            FileUploadUtils.assertAllowed(files);
            String url = fileService.uploadFile(files);
            return AjaxResult.success(url);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("上传失败");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("上传失败");
        }catch (FileSizeLimitExceededException e){
//            e.printStackTrace();
            return AjaxResult.fail("上传文件过大");
        }

    }

}

